import { post3, get1 } from '@/utils/Request'
import { getClient } from './aliOss';
import { v4 as uuidv4 } from 'uuid'
const uploadSingleApi = "/admin_server/file/upload"
const enabledOssUpload = process.env.VUE_APP_ENABLED_OSS_UPLOAD
const getStsTokenApi = "/admin_server/file/getStsToken"
export async function uploadSingle(file, suffixInput) {
    // 后台服务上传
    if (!enabledOssUpload || enabledOssUpload === 'false') {
        let form = new FormData();
        form.append("file", file);
        const { success, result } = await post3(uploadSingleApi, form)
        if (success) {
            return result
        }
        throw new Error("上传错误")
    } else {
        // OSS上传
        const { success, result } = await get1(getStsTokenApi)
        if (success) {
            let ossClient = getClient(result)
            const suffix = suffixInput ? "." + suffixInput : file.name.match(/.[^.]+$/)[0];
            const uuid = uuidv4()
            await ossClient.put(result.uploadPath + uuid + suffix, file)
            return {
                uuid: "/" + result.uploadPath + uuid + suffix,
                newFileName: uuid + suffix,
            }
        }
    }
}